from typing import Optional, Annotated
from fastapi import Depends, status, Request
from fastapi.security import APIKeyHeader
from jose import jwt, JWTError

from app.core.exceptions import APIException
from app.models.user_model import UserModel
from app.core.config import settings
from app.core.i18n import t
from app.core.security import is_token_blacklisted, add_user_token

# 创建 APIKeyHeader 实例
api_key_header = APIKeyHeader(name="Authorization", auto_error=False)


async def get_current_user(request: Request, authorization: str = Depends(api_key_header)) -> UserModel:
    """Validate Bearer token and return current user"""
    if not authorization:
        raise APIException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            message=t("auth.missing_token"),
        )

    if not authorization.startswith("Bearer "):
        raise APIException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            message=t("auth.invalid_token_format"),
        )

    try:
        token = authorization.replace("Bearer ", "")

        # 检查令牌是否在黑名单中
        if await is_token_blacklisted(token):
            raise APIException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                message=t("auth.token_blacklisted"),
            )

        payload = jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM])

        user_id = payload.get("sub")
        if not user_id:
            raise APIException(
                status_code=status.HTTP_403_FORBIDDEN,
                message=t("auth.invalid_token_payload"),
            )

        user = await UserModel.get_or_none(id=user_id, is_active=1)
        if not user:
            raise APIException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                message=t("auth.account_disabled"),
            )

        # 记录用户的活跃令牌
        exp = payload.get("exp")
        if exp:
            await add_user_token(user.id, token)

        request.state.user = user
        return user

    except JWTError as e:
        raise APIException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            message=t("auth.invalid_token"),
        ) from e


async def get_optional_user(request: Request, authorization: Optional[str] = None) -> Optional[UserModel]:
    """获取可选的当前用户，不抛出异常"""
    if not authorization:
        return None
    try:
        return await get_current_user(request, authorization)
    except APIException:
        return None


# 创建常用的依赖注入类型
# CurrentUser = Annotated[UserModel, Depends(get_current_user)]
CurrentUser = Annotated[UserModel, Depends(get_current_user)]
OptionalUser = Annotated[Optional[UserModel], Depends(get_optional_user)]
# CurrentUser = OptionalUser
